package com.kaibes.platform.file.client.api;

import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.kaibes.core.base.annotation.Description;
import com.kaibes.core.base.util.AesUtils;
import com.kaibes.platform.file.client.FileServerStrategy;
import com.kaibes.platform.file.client.db.FileServer;
import com.kaibes.web.api.ApiLink;
import com.kaibes.web.response.ResponseFactory;

@RestController
@RequestMapping("/files")
public class ClientFileApi {

    @Autowired
    private FileServerStrategy fileServerStrategy;
    
    @ApiLink("加密文件信息")
    @PostMapping("/encryptions")
    public ResponseEntity<?> encryption(@RequestBody @Description("加密明文") String cleartext) throws JsonProcessingException {
        FileServer serverInfo = fileServerStrategy.getFileServer();
        if (serverInfo == null) {
        	return ResponseFactory.badRequest("没有可用的存储服务器，请检查！");
        }
        
        try {
            String ciphertext = AesUtils.CBC.encrypt2String64(cleartext, serverInfo.getAesKey(), serverInfo.getAesIv());
            Map<String, Object> response = new HashMap<>();
            response.put("serverId", serverInfo.getId());
            response.put("host", serverInfo.getHost());
            response.put("userId", serverInfo.getUserId());
            response.put("ciphertext", ciphertext);
            return ResponseEntity.ok().body(response);
        } catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException | IllegalBlockSizeException
                | BadPaddingException | UnsupportedEncodingException | InvalidAlgorithmParameterException e) {
        	e.printStackTrace();
            return ResponseFactory.badRequest("信息加密失败");
        }
    }
    
}
